package com.neusoft.bigdata.hbase;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.MasterNotRunningException;
import org.apache.hadoop.hbase.ZooKeeperConnectionException;
import org.apache.hadoop.hbase.client.HBaseAdmin;

import com.neusoft.bigdata.hbase.util.CommonUtil;

/**
 * 创建表
 * 
 * @author lihzh
 * @date 2013-3-29 上午9:43:13
 */
public class ForPrepareTable extends CommonUtil {

	private static Configuration conf = null;

	static {
		Configuration HBASE_CONFIG = new Configuration();
		conf = HBaseConfiguration.create(HBASE_CONFIG);
	}

	/**
	 * @param args
	 * @author lihzh
	 * @throws Exception
	 * @date 2013-3-29 上午9:43:13
	 */
	public static void main(String[] args) throws Exception {
		try {
			createTable(ForPrepareData.TABLE_NAME_METRIC,
					ForPrepareData.COLUMN_FAMILY_NAME_METRICS,
					ForPrepareData.COLUMN_FAMILY_NAME_INFO);
			createTable(ForPrepareData.TABLE_NAME_METRIC_INDEX,
					ForPrepareData.COLUMN_FAMILY_NAME_ROWKEY);
			// 记录当前数据中监控数据的结束时间
			createTable(ForPrepareData.TABLE_NAME_NEXT_TIME,
					ForPrepareData.COLUMN_FAMILY_NAME_TIME);
			// 记录小时汇总数据
			createTable(TABLE_NAME_STATISTIC, CF_NAME_STINFO);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		// deleteTable(ForPrepareData.TABLE_NAME_METRIC);
		// deleteTable(ForPrepareData.TABLE_NAME_METRIC_INDEX);
		// deleteTable(ForPrepareData.TABLE_NAME_NEXT_TIME);
	}

	@SuppressWarnings("resource")
	private static void createTable(String tableName, String... families)
			throws IOException {
		HBaseAdmin admin = new HBaseAdmin(conf);
		if (admin.tableExists(tableName)) {
			System.out.println("table：" + tableName + " already exists!");
		} else {
			HTableDescriptor tableDesc = new HTableDescriptor(tableName);
			for (int i = 0; i < families.length; i++) {
				tableDesc.addFamily(new HColumnDescriptor(families[i]));
			}
			admin.createTable(tableDesc);
			System.out.println("create table " + tableName + " ok.");
		}
	}

	/**
	 * 删除表
	 */
	@SuppressWarnings("resource")
	public static void deleteTable(String tableName) throws Exception {
		try {
			HBaseAdmin admin = new HBaseAdmin(conf);
			admin.disableTable(tableName);
			admin.deleteTable(tableName);
			System.out.println("delete table " + tableName + " ok.");
		} catch (MasterNotRunningException e) {
			e.printStackTrace();
		} catch (ZooKeeperConnectionException e) {
			e.printStackTrace();
		}
	}
}
